<!doctype html>
{% import 'macro/svg.html' as SVG %}
{% import 'macro/oops.html' as OOPS %}
{% import 'macro/head.html' as HEAD %}
<html lang="en">
<head>
  {{ HEAD.meta_link() }}
  <title>NAStool</title>
  <!-- CSS files -->
  <link href="../static/css/tabler.min.css" rel="stylesheet"/>
  <link href="../static/css/demo.min.css" rel="stylesheet"/>
  <link href="../static/css/fullcalendar.min.css" rel="stylesheet"/>
  <link href="../static/css/jquery.filetree.css" rel="stylesheet"/>
  <link href="../static/css/dropzone.css" rel="stylesheet"/>
  <link href="../static/css/nprogress.css" rel="stylesheet"/>
  <!-- 附加样式 -->
  <link href="../static/css/style.css" rel="stylesheet"/>
  <!-- 站点图标 -->
  <style>
  {% for site_name, site_icon in SiteFavicons.items() %}
      .siteicon-{{ site_name|hash }} {
          background-image: url({{ site_icon }});
          background-size: cover;
          border: 0;
      }
  {% endfor %}
  </style>
</head>
<body class="layout-fluid">
<div class="page">
  <script src="../static/js/demo-theme.min.js"></script>
  <script type="module" src="../static/components/lit-index.js"></script>
  <!-- 解决密码填充问题 -->
  <span hidden><input type="text"><input type="password"></span>
  <layout-navbar id="navbar-menu" hidden
    layout-gopage="{{ GoPage }}"
    layout-appversion="{{ AppVersion }}"
    layout-userpris='{{ UserPris|tojson|safe }}'>
  </layout-navbar>
  <layout-searchbar hidden
      layout-username="{{ UserName }}"
      layout-systemflag="{{ SystemFlag }}"
      layout-userpris='{{ UserPris|tojson|safe }}'>
  </layout-searchbar>
  <div class="spinner-border" role="status" id="logo_animation" style="position:absolute;top:30%;left:calc(50% - 40px);width:80px;height:80px;"></div>
  <div class="page-wrapper" id="page_content" hidden="">
    {{ OOPS.loading() }}
  </div>
</div>
<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasEnd" aria-labelledby="消息中心">
  <div class="offcanvas-header">
    <h2 class="offcanvas-title" id="offcanvasEndLabel">消息中心</h2>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body" style="padding:0.5rem 0.5rem;">
    <div class="list-group list-group-flush" id="system-messages">
    </div>
    <div class="mt-3" align="center">
      <button class="btn btn-primary" type="button" data-bs-dismiss="offcanvas">
        关闭
      </button>
    </div>
  </div>
</div>
<!-- 等待框 -->
<div class="modal" id="modal-wait" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-full-width modal-dialog-centered" role="document">
    <div class="spinner-border text-primary m-auto"></div>
  </div>
</div>
<!-- 进度框 -->
<div class="modal modal-blur" id="modal-process" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-md modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="card border-0" style="overflow:hidden">
        <div class="progress rounded-0">
          <div class="progress-bar progress-bar-striped progress-bar-animated" id="modal_process_bar"
               style="width: 0" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
        <div class="card-body text-center">
          <h3 class="card-title strong" id="modal_process_title">
          </h3>
          <small class="text-muted" id="modal_process_text">请稍候...</small>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 危险确认提示框 -->
<div class="modal modal-blur fade" id="system-confirm-modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
    <div class="modal-content">
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      <div class="modal-status bg-danger"></div>
      <div class="modal-body text-center py-4">
       <span class="mb-2 text-danger">{{ SVG.alert_triangle('icon-lg') }}</span>
        <h3>确认</h3>
        <div class="text-muted text-wrap" id="system_confirm_message" style="overflow: hidden">是否确定？</div>
      </div>
      <div class="modal-footer">
        <div class="w-100">
          <div class="row">
            <div class="col">
              <a href="#" class="btn w-100" data-bs-dismiss="modal">
                取消
              </a>
            </div>
            <div class="col">
              <button class="btn btn-danger w-100" id="system_confirm_btn">
                确定
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 成功带后续操作提示框 -->
<div class="modal modal-blur fade" id="system-success-action-modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
    <div class="modal-content">
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      <div class="modal-status bg-success"></div>
      <div class="modal-body text-center py-4">
        <span class="mb-2 text-green">{{ SVG.circle_check('icon-lg') }}</span>
        <h3>成功</h3>
        <div class="text-muted text-wrap" id="system_success_action_message" style="overflow: hidden">操作成功！</div>
      </div>
      <div class="modal-footer">
        <div class="w-100">
          <div class="row">
            <div class="col" id="system_success_action_div">
              <button class="btn w-100" id="system_success_action_btn">
                操作
              </button>
            </div>
            <div class="col">
              <button class="btn btn-success w-100" data-bs-dismiss="modal">
                确定
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 询问框 -->
<div class="modal modal-blur fade" id="system-ask-modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-body">
        <div class="modal-title">询问</div>
        <div id="system_ask_message" class="text-wrap" style="overflow: hidden">是否执行？</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-link link-secondary me-auto" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-danger" id="system_ask_btn">确定</button>
      </div>
    </div>
  </div>
</div>
<!-- 成功提示 -->
<div class="modal modal-blur fade" id="system-success-modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
    <div class="modal-content">
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      <div class="modal-status bg-success"></div>
      <div class="modal-body text-center py-4">
        <span class="mb-2 text-green">{{ SVG.circle_check('icon-lg') }}</span>
        <h3>成功</h3>
        <div class="text-muted text-wrap" id="system_success_message" style="overflow: hidden">成功！</div>
      </div>
      <div class="modal-footer">
        <div class="w-100">
          <div class="row">
            <div class="col">
              <a href="javascript:void(0)" id="system_success_modal_btn" class="btn btn-success w-100"
                 data-bs-dismiss="modal">
                确定
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 失败提示 -->
<div class="modal modal-blur fade" id="system-fail-modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
    <div class="modal-content">
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      <div class="modal-status bg-warning"></div>
      <div class="modal-body text-center py-4">
        <span class="mb-2 text-warning">{{ SVG.alert_triangle('icon-lg') }}</span>
        <h3>失败</h3>
        <div class="text-muted text-wrap" id="system_fail_message" style="overflow:hidden">失败！</div>
      </div>
      <div class="modal-footer">
        <div class="w-100">
          <div class="row">
            <div class="col">
              <a href="#" id="system_fail_modal_btn" class="btn btn-warning w-100" data-bs-dismiss="modal">
                确定
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 媒体详情 -->
<div class="modal modal-blur fade" id="system-media-modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="card">
        <div class="ribbon ribbon-top ribbon-bookmark bg-purple" id="system_media_vote"></div>
        <div class="row row-0">
          <div class="col-3 d-none d-lg-block">
            <custom-img id="system_media_poster"
                        img-class="w-100 h-100 object-cover"
                        img-ratio="150%"
            ></custom-img>
          </div>
          <div class="col">
            <div class="card-body">
              <h4 class="card-title mb-3">
                <a id="system_media_name_link" href="#" target="_blank"><strong
                        id="system_media_name"></strong></a><br/>
                <span class="text-muted" id="system_release_date"></span>
              </h4>
              <div class="text-muted mb-3" id="system_media_overview">
              </div>
              <div id="system_sites_info"></div>
            </div>
          </div>
        </div>
        <div class="d-flex">
          <a href="#" target="_blank" class="card-btn" id="system_media_url_btn">
            详情
          </a>
          <a href="javascript:void(0)" data-bs-toggle="dropdown" class="dropdown-toggle card-btn"
             id="system_media_rss_btn">
            订阅
          </a>
          <div class="dropdown-menu" id="system_media_rss_dropdown"></div>
          <a href="javascript:void(0)" class="card-btn" id="system_media_search_btn"
             style="border-left:1px solid var(--tblr-border-color)">
            搜索
          </a>
          <a href="javascript:void(0)" class="card-btn" id="system_media_refresh_btn"
             style="border-left:1px solid var(--tblr-border-color)">
            刷新
          </a>
          <a href="javascript:void(0)" class="card-btn d-none d-md-block" data-bs-dismiss="modal">
            关闭
          </a>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 实时日志 -->
<div class="modal modal-blur fade" id="modal-logging" tabindex="-1" role="dialog" aria-hidden="true"
     data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <div class="select_logger">
          <h5 class="modal-title">实时日志</h5>
           <div class="dropdown">
              <a href='#' class="btn-action" data-bs-toggle="dropdown" aria-expanded="false" onclick="get_logging_source()">
                {{ SVG.log_select() }}
              </a>
              <div class="dropdown-menu dropdown-menu-end" id="dropdown-menu-logger">
              </div>
           </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="logging_close_head"></button>
      </div>
      <div id="logging_table" class="table-responsive" style="overflow-y: auto; max-height: 60rem;">
      <table class="table table-vcenter card-table table-hover table-striped">
        <thead>
          <tr>
            <th class="w-3">时间</th>
            <th class="w-3">来源</th>
            <th>内容</th>
          </tr>
        </thead>
        <tbody id="logging_content" class="table-tbody">
        </tbody>
      </table>
      </div>
      <div class="modal-footer">
        <a href="javascript:pause_logging()" class="btn btn-link me-auto" id="logging_stop_btn">
          暂停
        </a>
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="logging_close_btn">关闭</button>
      </div>
    </div>
  </div>
</div>
<!-- 订阅季 -->
<div class="modal modal-blur fade" id="system-rss-seasons" tabindex="-1" role="dialog" aria-hidden="true"
     data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">选择订阅季</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col">
            <div class="mb-3">
              <div class="form-selectgroup" id="system_rss_seasons_group">
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <a href="javascript:void(0)" id="system_rss_seasons_btn" class="btn btn-primary">确定</a>
      </div>
    </div>
  </div>
</div>
<!-- 手动订阅 -->
<div class="modal modal-blur fade" id="modal-manual-rss" tabindex="-1" role="dialog" aria-hidden="true"
     data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="rss_modal_title">新增订阅</h5>
        <input type="hidden" id="rss_id">
        <input type="hidden" id="rss_type">
        <input type="hidden" id="rss_tmdbid">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-lg-6">
            <div class="mb-3">
              <label class="form-label required">标题</label>
              <input type="text" value="" id="rss_name" class="form-control" placeholder="标题">
            </div>
          </div>
          <div class="col-lg-2">
            <div class="mb-3">
              <label class="form-label required">年份</label>
              <input type="text" value="" id="rss_year" class="form-control" placeholder="年份">
            </div>
          </div>
          <div class="col-lg-4">
            <div class="mb-3">
              <label class="form-label">自定义搜索词</label>
              <input type="text" value="" id="rss_keyword" class="form-control" placeholder="留空使用TMDB数据">
            </div>
          </div>
        </div>
        <div class="row" id="rss_tv_season_div">
          <div class="col-lg-4">
            <div class="mb-3">
              <label class="form-label required">季</label>
              <select class="form-select" id="rss_season">
                <option value="" selected>请选择</option>
              </select>
            </div>
          </div>
          <div class="col-lg-4">
            <div class="mb-3">
              <label class="form-label">总集数 <span class="form-help"
                                                     title="可留空应用TMDB剧集信息"
                                                     data-bs-toggle="tooltip">?</span></label>
              <input type="text" value="" id="rss_total_ep" class="form-control" placeholder="总集数">
            </div>
          </div>
          <div class="col-lg-4">
            <div class="mb-3">
              <label class="form-label">开始订阅集数</label>
              <input type="text" value="" id="rss_current_ep" class="form-control" placeholder="开始订阅集数">
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-xl-4">
            <div class="mb-3">
              <label class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="fuzzy_match"
                       onclick="change_match_check(this)">
                <span class="form-check-label">模糊匹配 <span class="form-help"
                                                              title="开启后不检查TMDB是否有媒体信息，只要种子名称、标题、年份任一匹配关键字即会下载，此时标题可以配置正则表达式实现模糊匹配"
                                                              data-bs-toggle="tooltip">?</span></span>
              </label>
            </div>
          </div>
          <div class="col-xl-4">
            <div class="mb-3">
              <label class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="over_edition"
                       onclick="change_over_edition_check(this)">
                <span class="form-check-label">洗版 <span class="form-help"
                                                          title="开启洗版后不会检查本地是否已存在，满足订阅条件即会下载；除非匹配了对应的过滤规则中最高优先级的那条规则否则不会删除订阅（未明确过滤规则时使用默认规则），同一优先级的资源只下载一次；多个资源下载后如命名一致，则只会保留文件体积较大的，如需都保留则需要在文件重命名规则中增加相关要素以做区分"
                                                          data-bs-toggle="tooltip">?</span></span>
              </label>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-lg-3">
            <div class="mb-3">
              <label class="form-label">质量</label>
              <select class="form-select" id="rss_restype">
                <option value="" selected>全部</option>
                {% for Restype in RestypeDict %}
                  <option value="{{ Restype }}">{{ Restype }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
          <div class="col-lg-3">
            <div class="mb-3">
              <label class="form-label">分辨率</label>
              <select class="form-select" id="rss_pix">
                <option value="" selected>全部</option>
                {% for Pix in PixDict %}
                  <option value="{{ Pix }}">{{ Pix }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
          <div class="col-lg-3">
            <div class="mb-3">
              <label class="form-label">制作组/字幕组</label>
              <input type="text" value="" id="rss_team" class="form-control" placeholder="支持正则表达式">
            </div>
          </div>
          <div class="col-lg-3">
            <div class="mb-3">
              <label class="form-label">过滤规则 <span class="form-help"
                                                       title="质量、分辨率与过滤规则为“与”的关系，过滤规则不选择时将使用站点的过滤规则，站点也未设置过滤规则时将使用默认过滤规则"
                                                       data-bs-toggle="tooltip">?</span></label>
              <select class="form-select" id="rss_rule">
              </select>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-lg-4">
            <div class="mb-3">
              <label class="form-label">下载设置</label>
              <select class="form-select" id="rss_download_setting"
                      onchange="refresh_savepath_select('rss_save_path', true, $(this).val())">
              </select>
            </div>
          </div>
          <div class="col-lg-8">
            <div class="mb-3">
              <label class="form-label">保存路径</label>
              <select class="form-select" id="rss_save_path" aria-label="保存目录">
              </select>
            </div>
          </div>
        </div>
        <div class="row rss_sites_container" id="rss_sites_div">
          <div class="mb-3">
            <div class="btn-list">
              <label class="form-label">订阅站点</label>
              <a href="javascript:void(0)" class="ms-auto" onclick="select_btn_SelectALL(this, 'rss_sites')">全选</a>
            </div>
            <div class="form-selectgroup" id="rss_sites_group"></div>
          </div>
        </div>
        <div class="row rss_sites_container" id="rss_search_sites_div">
          <div class="mb-3">
            <div class="btn-list">
              <label class="form-label">搜索站点</label>
              <a href="javascript:void(0)" class="ms-auto" onclick="select_btn_SelectALL(this, 'search_sites')">全选</a>
            </div>
            <div class="form-selectgroup" id="rss_search_sites_group"></div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <a href="#" class="btn btn-link text-red me-auto" id="rss_delete_btn">
          取消订阅
        </a>
        <div class="btn-list">
          <a href="javascript:add_rss_manual(true)" name="rss_add_btn" class="btn btn-secondary">添加并继续</a>
          <a href="javascript:add_rss_manual(false)" name="rss_add_btn" class="btn btn-primary">添加</a>
          <a href="javascript:add_rss_manual(false)" name="rss_edit_btn" class="btn btn-primary">确定</a>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 手动识别 -->
<div class="modal modal-blur fade" id="modal-media-identification" tabindex="-1" role="dialog" aria-hidden="true"
     data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="rename_header">手动识别</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row" id="rename_path_div">
          <div class="col-lg-9">
            <div class="mb-3">
              <label class="form-label required">路径</label>
              <input type="text" id="rename_path" class="form-control" readonly>
              <input type="hidden" id="rename_source">
              <input type="hidden" id="rename_manual_type">
              <input type="hidden" id="unknown_id">
              <input type="hidden" id="transferlog_id" class="form-control">
            </div>
          </div>
          <div class="col-lg-3">
            <div class="mb-3">
              <label class="form-label required">转移方式</label>
              <select id="rename_syncmod_manual" class="form-select">
                {% for mode in RmtModeDict %}
                  <option value="{{ mode.value }}" {% if SyncMod==mode.value %}selected{% endif %}>{{ mode.name }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
        </div>
        <div class="mb-3" id="rename_inpath_div">
          <label class="form-label required">输入路径</label>
          <input type="text" id="rename_inpath" class="form-control filetree-folders-only"
                 placeholder="需要转移的目录或文件"
                 autocomplete="off">
        </div>
        <div class="row" id="rename_outpath_div">
          <div class="col-lg-9">
            <div class="mb-3">
              <label class="form-label">输出路径</label>
              <input type="text" id="rename_outpath" class="form-control filetree-folders-only"
                     placeholder="转移后文件存储路径，留空则转移至媒体库" autocomplete="off">
            </div>
          </div>
          <div class="col-lg-3">
            <div class="mb-3">
              <label class="form-label required">转移方式</label>
              <select id="rename_syncmod_customize" class="form-select">
                <option value="link" {% if SyncMod=="link" %} selected="selected" {% endif %}>硬链接</option>
                <option value="softlink" {% if SyncMod=="softlink" %} selected="selected" {% endif %}>软链接</option>
                <option value="copy" {% if SyncMod=="copy" %} selected="selected" {% endif %}>复制</option>
                <option value="move" {% if SyncMod=="move" %} selected="selected" {% endif %}>移动</option>
                <option value="rclonecopy" {% if SyncMod=="rclonecopy" %} selected="selected" {% endif %}>Rclone复制
                </option>
                <option value="rclone" {% if SyncMod=="rclone" %} selected="selected" {% endif %}>Rclone移动</option>
                <option value="miniocopy" {% if SyncMod=="miniocopy" %} selected="selected" {% endif %}>Minio复制
                </option>
                <option value="minio" {% if SyncMod=="minio" %} selected="selected" {% endif %}>Minio移动</option>
              </select>
            </div>
          </div>
        </div>
        <label class="form-label">类型</label>
        <div class="form-selectgroup-boxes row mb-3">
          <div class="col-lg-4">
            <div class="mb-1">
              <label class="form-selectgroup-item">
                <input type="radio" id="rename_type_mov" name="rename_type" value="MOV" class="form-selectgroup-input"
                       checked>
                <span class="form-selectgroup-label d-flex align-items-center p-3">
                    <span class="me-3">
                      <span class="form-selectgroup-check"></span>
                    </span>
                    <span class="form-selectgroup-label-content">
                      <span class="form-selectgroup-title strong mb-1">电影</span>
                    </span>
                  </span>
              </label>
            </div>
          </div>
          <div class="col-lg-4">
            <div class="mb-1">
              <label class="form-selectgroup-item">
                <input type="radio" id="rename_type_tv" name="rename_type" value="TV" class="form-selectgroup-input">
                <span class="form-selectgroup-label d-flex align-items-center p-3">
                    <span class="me-3">
                      <span class="form-selectgroup-check"></span>
                    </span>
                    <span class="form-selectgroup-label-content">
                      <span class="form-selectgroup-title strong mb-1">电视剧</span>
                    </span>
                  </span>
              </label>
            </div>
          </div>
          <div class="col-lg-4">
            <div class="mb-1">
              <label class="form-selectgroup-item">
                <input type="radio" id="rename_type_anime" name="rename_type" value="ANIME"
                       class="form-selectgroup-input">
                <span class="form-selectgroup-label d-flex align-items-center p-3">
                    <span class="me-3">
                      <span class="form-selectgroup-check"></span>
                    </span>
                    <span class="form-selectgroup-label-content">
                      <span class="form-selectgroup-title strong mb-1">动漫</span>
                    </span>
                  </span>
              </label>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-lg-4">
            <div class="mb-3">
              <label class="form-label">TMDB ID</label>
              <div class="input-group">
                <input type="text" id="rename_tmdb" class="form-control" placeholder="留空自动识别">
                <button class="btn" type="button" onclick="show_search_tmdbid_modal('rename_tmdb', 'modal-media-identification')">查询</button>
              </div>
            </div>
          </div>
          <div class="col-lg-4" id="rename_season_div">
            <div class="mb-3">
              <label class="form-label">季</label>
              <select class="form-select" id="rename_season">
                <option value="" selected>请选择</option>
              </select>
            </div>
          </div>
          <div class="col-lg-4" id="rename_min_filesize_div">
            <div class="mb-3">
              <label class="form-label">最小文件大小 <span class="form-help" title="留空将使用基础设置中的转移最小文件大小设置，如不限制大小需输入0" data-bs-toggle="tooltip">?</span></label>
              <input type="text" id="rename_min_filesize" class="form-control" placeholder="最小文件大小(MB)">
            </div>
          </div>
          <div class="col-lg-12" id="rename_episode_div">
            <div class="mb-3">
              <label class="form-label">集数定位 <span class="form-help"
                                                       title="3个都不填，用默认识别<br>1、{ep}: 标定集数位置，例如：<br>&nbsp;&nbsp;&nbsp;&nbsp;'(BD)十二国記 第45話「東の海神 西の滄海 五章」(1440x1080 x264-10bpp flac).mkv'<br>&nbsp;&nbsp;&nbsp;&nbsp;'(BD)十二国記 第32話「風の万里 黎明の空　九章」(1440x1080 x264-10bpp flac).mkv'<br>&nbsp;&nbsp;&nbsp;&nbsp;此处可以填'(BD)十二国記 第{ep}話{a}(1440x1080 x264-10bpp flac).mkv' ep表示集，a表示理解成一个变量，随意用一个变量表示，如果没有变化的部分，只标定ep就行。<br>2、起始集[, 终止集]：裁定处理集数范围， 如果输入是文件，输出就是单个文件，如果输入是目录，输出可以根据填的值批量识别，<br>&nbsp;&nbsp;&nbsp;&nbsp;例如 '1' 表示第一集, '2,4' 只取第2集到第4集，'1-2'表示第1-2集，此选项优先级最高。<br>3、集数偏移：例如ep定位出集数是11, 实际是第1集, 此处填-10, 以应付多季合集的场景。"
                                                       data-bs-toggle="tooltip" data-bs-html="true">?</span></label>
              <div class="row">
                <div class="col-4">
                  <input type="text" id="rename_episode" class="form-control" placeholder="{ep}定位集数">
                </div>
                <div class="col-4">
                  <input type="text" id="rename_episode_details" class="form-control"
                         placeholder="起始集[,终止集]，如1或1,2">
                </div>
                <div class="col-4">
                  <input type="text" id="rename_episode_offset" class="form-control" placeholder="集数偏移，如-10">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-link me-auto" data-bs-dismiss="modal">取消</button>
        <button type="button" id="identification_action_btn" class="btn btn-primary"
                onclick="manual_media_transfer()">转移
        </button>
      </div>
    </div>
  </div>
</div>
<!-- 手动下载 -->
<div class="modal modal-blur fade" id="modal-search-download" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-md modal-dialog-centered" role="document">
    <input type="hidden" id="search_download_id">
    <input type="hidden" id="search_download_name">
    <div class="modal-content">
      <div class="modal-body">
        <div class="modal-title">添加下载</div>
        <div class="row mt-3">
          <div class="col-md">
            <div class="form-floating mb-1">
              <select class="form-select" id="search_download_setting" aria-label="下载设置"
                  onchange="refresh_savepath_select('search_download_dir', true, $(this).val())">
              </select>
              <label for="floatingSelect">下载设置</label>
            </div>
          </div>
          <div class="col-md">
            <div class="form-floating mb-1">
              <select class="form-select" id="search_download_dir" aria-label="保存目录"></select>
              <label for="floatingSelect">保存目录</label>
            </div>
          </div>
        </div>
        <form class="dropzone mt-2" id="torrent_files" action="/upload">
          <div class="fallback">
            <input name="file" type="file" accept="*.zip" />
          </div>
          <div class="dz-message">
            <h3 class="dropzone-msg-title">上传种子文件</h3>
            <span class="dropzone-msg-desc">点击或者拖动种子文件到此处</span>
          </div>
        </form>
        <textarea class="form-control mt-2" id="torrent_magnets" rows="8" placeholder="magnet:?xt=urn:btih:xxx，换行添加多个磁链"></textarea>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-link link-secondary me-auto" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="search_download_btn" title="立即开始下载">
          下载
        </button>
      </div>
    </div>
  </div>
</div>
<!-- 根据名称查找TMDBID的对话框 -->
<div class="modal modal-blur fade" id="search-tmdbid-modal" tabindex="-1" role="dialog" aria-hidden="true"
     data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">查询TMDBID</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col">
            <input id="search_tmdbid_name" type="text" class="form-control" placeholder="输入名称查询">
          </div>
          <div class="col-auto">
            <button onclick="search_tmdbid_by_name('search_tmdbid_name', 'search_tmdbid_list')" class="btn btn-primary btn-icon" aria-label="Button">
              {{ SVG.search() }}
            </button>
          </div>
        </div>
        <div class="row mt-3">
          <div class="list-group list-group-flush" id="search_tmdbid_list">
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button id="search_tmdbid_btn" class="btn btn-primary">确定</button>
      </div>
    </div>
  </div>
</div>
<div class="modal modal-blur fade" id="modal-search-advanced" tabindex="-1" role="dialog" aria-hidden="true"
     data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">高级搜索</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-12 col-lg-4">
            <div class="mb-3">
              <label class="form-label">类型</label>
              <select class="form-select" id="advanced_search_type">
                <option value="" selected>全部</option>
                <option value="电影">电影</option>
                <option value="电视剧">电视剧</option>
              </select>
            </div>
          </div>
          <div class="col-12 col-lg-4">
            <div class="mb-3">
              <label class="form-label required">名称</label>
              <input type="text" value="" id="advanced_search_name" class="form-control"
                     placeholder="电影/电视剧名称">
            </div>
          </div>
          <div class="col-12 col-lg-2">
            <div class="mb-3">
              <label class="form-label">年份</label>
              <input type="text" value="" id="advanced_search_year" class="form-control" placeholder="20xx">
            </div>
          </div>
          <div class="col-12 col-lg-2">
            <div class="mb-3">
              <label class="form-label">季</label>
              <select class="form-select" id="advanced_search_season">
                <option value="" selected>全部</option>
              </select>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-12 col-lg-4">
            <div class="mb-3">
              <label class="form-label">站点</label>
              <select class="form-select" id="advanced_search_site">
                <option value="" selected>全部</option>
                {% for site in Indexers %}
                  <option value="{{ site.name }}">{{ site.name }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
          <div class="col-12 col-lg-4">
            <div class="mb-3">
              <label class="form-label">质量</label>
              <select class="form-select" id="advanced_search_restype">
                <option value="" selected>全部</option>
                {% for Restype in RestypeDict %}
                  <option value="{{ Restype }}">{{ Restype }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
          <div class="col-12 col-lg-4">
            <div class="mb-3">
              <label class="form-label">分辨率</label>
              <select class="form-select" id="advanced_search_pix">
                <option value="" selected>全部</option>
                {% for Pix in PixDict %}
                  <option value="{{ Pix }}">{{ Pix }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
          <div class="col-12 col-lg-4">
            <div class="mb-3">
              <label class="form-label">促销</label>
              <select class="form-select" id="advanced_sp_state">
                <option value="* *" selected>全部</option>
                <option value="1.0 1.0">普通</option>
                <option value="1.0 0.0">免费</option>
                <option value="2.0 1.0">2X</option>
                <option value="2.0 0.0">2X免费</option>
                <option value="1.0 0.5">50%</option>
                <option value="2.0 0.5">2X 50%</option>
                <option value="1.0 0.7">70%</option>
                <option value="1.0 0.3">30%</option>
              </select>
            </div>
          </div>
          <div class="col-12 col-lg-8">
            <div class="mb-3">
              <label class="form-label">过滤规则</label>
              <select id="advanced_search_rule" class="form-control"></select>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button onclick="search_media_advanced()" id="search_advanced_btn"
                class="btn btn-primary">开始搜索
        </button>
      </div>
    </div>
  </div>
</div>
<script src="../static/js/libs/list.min.js"></script>
<script src="../static/js/jquery-3.3.1.min.js"></script>
<script src="../static/js/tabler.min.js"></script>
<script src="../static/js/demo.min.js"></script>
<script src="../static/js/echarts.min.js"></script>
<script src="../static/js/numeral.min.js"></script>
<script src="../static/js/fullcalendar.min.js"></script>
<script src="../static/js/locales/zh-cn.js"></script>
<script src="../static/js/jquery.filetree.js"></script>
<script src="../static/js/dropzone-min.js"></script>
<script src="../static/js/dom-to-image.min.js"></script>
<script src="../static/js/FileSaver.min.js"></script>
<script src="../static/js/nprogress.js"></script>
<script src="../static/js/ace.js"></script>
<script src="../static/js/util.js"></script>
<!-- 提示弹窗 -->
<script type="text/javascript">
  // 显示全局加载蒙版
  function show_wait_modal(blur) {
    if (blur) {
      $('#modal-wait').addClass('modal-blur');
    } else {
      $('#modal-wait').removeClass('modal-blur');
    }
    $("#modal-wait").modal("show");
  }

  // 关闭全局加载蒙版
  function hide_wait_modal() {
    $("#modal-wait").modal("hide");
  }

  // 刷新进度
  let refresh_process_flag = false;
  let refresh_fail_count = 0;
  function refresh_process(type) {
    if (!refresh_process_flag) {
      return;
    }
    ajax_post("refresh_process", {type: type}, function (ret) {
      if (ret.code === 0 && ret.value <= 100) {
        $("#modal_process_bar").attr("style", "width: " + ret.value + "%").attr("aria-valuenow", ret.value);
        $("#modal_process_text").text(ret.text);
      } else {
        refresh_fail_count = refresh_fail_count + 1;
      }
      if (refresh_fail_count < 5) {
        setTimeout("refresh_process('"+type+"')", 200);
      }
    }, true, false);
  }

  // 显示全局进度框
  function show_refresh_process(title, type) {
    if (title) {
      $("#modal_process_title").text(title);
    } else {
      $("#modal_process_title").hide();
    }
    $("#modal_process_bar").attr("style", "width: 0%").attr("aria-valuenow", 0);
    $("#modal_process_text").text("请稍候...");
    $("#modal-process").modal("show");
    //刷新进度
    refresh_process_flag = true;
    refresh_fail_count = 0;
    refresh_process(type);
  }

  // 关闭全局进度框
  function hide_refresh_process() {
    refresh_process_flag = false;
    $("#modal-process").modal("hide");
  }

  // 显示确认提示框
  function show_confirm_modal(title, func) {
    $("#system_confirm_message").text(title);
    $("#system_confirm_btn").unbind('click').click(func);
    $("#system-confirm-modal").modal("show");
  }

  // 隐藏确认提示框
  function hide_confirm_modal() {
    $("#system-confirm-modal").modal("hide");
  }

  // 显示询问提示框
  function show_ask_modal(title, func) {
    $("#system_ask_message").text(title);
    $("#system_ask_btn").unbind('click').click(func);
    $("#system-ask-modal").modal("show");
  }

  // 隐藏询问提示框
  function hide_ask_modal() {
    $("#system-ask-modal").modal("hide");
  }

  // 显示成功提示
  function show_success_modal(title, func) {
    $("#system_success_message").text(title);
    if (func) {
      $("#system_success_modal_btn").unbind('click').click(func);
    } else {
      $("#system_success_modal_btn").unbind('click');
    }
    $("#system-success-modal").modal("show");
  }

  // 显示失败提示
  function show_fail_modal(title, func) {
    $("#system_fail_message").text(title);
    if (func) {
      $("#system_fail_modal_btn").unbind('click').click(func);
    } else {
      $("#system_fail_modal_btn").unbind('click');
    }
    $("#system-fail-modal").modal("show");
  }

</script>

<!-- 媒体弹窗 -->
<script type="text/javascript">

  //搜索
  function media_search(tmdbid, title, type) {
    const param = {"tmdbid": tmdbid, "search_word": title, "media_type": type};
    show_refresh_process("正在搜索 " + title + " ...", "search");
    ajax_post("search", param, function (ret) {
      hide_refresh_process();
      if (ret.code === 0) {
        navmenu('search?s=' + title)
      } else {
        show_fail_modal(ret.msg);
      }
    }, true, false);
  }

  //显示媒体详情弹窗
  function show_mediainfo_modal(rtype, name, year, mediaid, page, rssid) {
    if (!page) {
      page = "";
    }
    if (!rssid) {
      rssid = "";
    }
    ajax_post("media_info", {
      "id": mediaid,
      "title": name,
      "year": year,
      "type": rtype,
      "page": page,
      "rssid": rssid
    }, function (ret) {
      if (ret.code === 0) {
        //显示信息
        $("#system_media_name").text(ret.title);
        $("#system_release_date").text(ret.release_date)
        if (ret.poster_path) {
          $("#system_media_poster").attr("img-src", ret.poster_path);
        } else {
          $("#system_media_poster").attr("img-src", "../static/img/no-image.png");
        }
        if (ret.overview && ret.overview.length > 200) {
          $("#system_media_overview").text(ret.overview.substr(0, 200) + " ...");
        } else {
          $("#system_media_overview").text(ret.overview);
        }
        if (!ret.vote_average || ret.vote_average == "0") {
          $("#system_media_vote").hide();
        } else {
          $("#system_media_vote").text(ret.vote_average).show();
        }
        //订阅按钮、搜索按钮
        if ($("#system_media_rss_dropdown").hasClass("show")) {
          $("#system_media_rss_btn").dropdown("toggle");
        }
        //先隐藏所有按钮，有需要再显示
        $("#system_media_rss_btn").hide();
        $("#system_media_search_btn").hide();
        $("#system_media_refresh_btn").hide();
        $("#system_media_url_btn").hide();
        if (ret.rssid) {
          //取消订阅按钮
          $("#system_media_rss_btn").text("取消订阅")
              .removeAttr("data-bs-toggle")
              .removeClass("dropdown-toggle")
              .attr("href", 'javascript:remove_rss_media("' + ret.title + '","' + ret.year + '","' + ret.type + '","' + ret.rssid + '","' + ret.page + '")')
              .show();
          //搜索按钮
          $("#system_media_search_btn").text("搜索")
              .attr("href", 'javascript:search_mediainfo_media("' + ret.tmdbid + '", "' + ret.title + '", "' + ret.type_str + '")')
              .show();
          //刷新和编辑按钮
          if (ret.page.startsWith("movie_rss") || ret.page.startsWith("tv_rss")) {
            //编辑
            $("#system_media_url_btn").text("编辑")
                .removeAttr("target")
                .attr("href", "javascript:show_edit_rss_media_modal('" + ret.rssid + "', '" + ret.type_str + "')")
                .show();
            //刷新
            $("#system_media_refresh_btn").text("刷新")
                .attr("href", 'javascript:refresh_rss_media("' + ret.type + '","' + ret.rssid + '","' + ret.page + '")')
                .show();
          } else {
            //详情按钮
            $("#system_media_url_btn").text("详情")
                .attr("target", "_blank")
                .attr("href", 'javascript:navmenu("media_detail?type='+ret.type+'&id='+ret.tmdbid+'")')
                .show();
          }
        } else {
          //详情按钮
          $("#system_media_url_btn").text("详情")
              .attr("target", "_blank")
              .attr("href", 'javascript:navmenu("media_detail?type='+ret.type+'&id='+ret.tmdbid+'")')
              .show();
          //订阅按钮
          $("#system_media_rss_btn").text("订阅");
          $("#system_media_rss_dropdown").empty();
          if (ret.seasons.length === 0) {
            $("#system_media_rss_btn").removeAttr("data-bs-toggle")
                .removeClass("dropdown-toggle")
                .attr("href", 'javascript:add_rss_media("' + ret.title + '","' + ret.year + '","' + ret.type + '","' + ret.tmdbid + '","' + ret.page + '","")')
          } else {
            $("#system_media_rss_btn").prop("data-bs-toggle", "dropdown")
                .addClass("dropdown-toggle")
                .attr("href", 'javascript:$("#system_media_rss_btn").dropdown("toggle")')
            //订阅季的下拉框
            for (let i = 0; i < ret.seasons.length; i++) {
              $("#system_media_rss_dropdown").append('<a class="dropdown-item" href=\'javascript:add_rss_media("' + ret.title + '","' + ret.year + '","' + ret.type + '","' + ret.tmdbid + '","' + ret.page + '","' + ret.seasons[i].num + '")\'>' + ret.seasons[i].text + '</a>');
            }
          }
          $("#system_media_rss_btn").show();
          //搜索按钮
          $("#system_media_search_btn").text("搜索")
              .attr("href", 'javascript:search_mediainfo_media("' + ret.tmdbid + '", "' + ret.title + '", "' + ret.type_str + '")')
              .show();
        }
        $("#system_media_name_link").attr("href", ret.link_url);
        //弹窗
        $("#system-media-modal").modal("show");
      } else if (ret.code === 1) {
        if (ret.rssid) {
          show_edit_rss_media_modal(ret.rssid, ret.type_str);
        } else {
          show_fail_modal(`${name} 未查询到TMDB媒体信息！`);
        }
      }
    });
  }

  //隐藏媒体详情
  function hide_mediainfo_modal() {
    $("#system-media-modal").modal("hide");
  }

  //新增订阅
  function add_rss_media(name, year, type, mediaid, page, season, func) {
    hide_mediainfo_modal();
    let data = {
      "name": name,
      "type": type,
      "year": year,
      "mediaid": mediaid,
      "page": page,
      "season": season
    };
    ajax_post("add_rss_media", data, function (ret) {
      if (ret.code === 0) {
        if (ret.page) {
          navmenu(ret.page);
        } else {
          if (func) {
            func();
          }
          show_rss_success_modal(ret.rssid, type, name + " 添加订阅成功！")
        }
      } else {
        show_fail_modal(`${ret.name} 添加订阅失败：${ret.msg}！`);
      }
    });
  }

  // 取消订阅
  function remove_rss_media(name, year, type, rssid, page, tmdbid, func) {
    hide_mediainfo_modal();
    let data = {"name": name, "type": type, "year": year, "rssid": rssid, "page": page, "tmdbid": tmdbid};
    ajax_post("remove_rss_media", data, function (ret) {
      if (func) {
        func();
      } else if (ret.page) {
        window_history_refresh();
      } else {
        show_success_modal(ret.name + " 已从订阅中移除！");
      }
    });
  }

  // 刷新订阅
  function refresh_rss_media(type, rssid, page) {
    hide_mediainfo_modal();
    ajax_post("refresh_rss", {"type": type, "rssid": rssid, "page": page}, function (ret) {
      if (ret.page) {
        window_history_refresh();
      } else {

      }
    });
  }

  //显示订阅季选择框
  function show_rss_seasons_modal(name, year, type, mediaid, seasons, func) {
    let system_rss_seasons_content = "";
    for (let season of seasons) {
      system_rss_seasons_content += `<label class="form-selectgroup-item">
                                      <input type="checkbox" name="system_rss_season" value="${season.num}" class="form-selectgroup-input">
                                      <span class="form-selectgroup-label">${season.text}</span>
                                     </label>`;
    }
    $("#system_rss_seasons_group").empty().append(system_rss_seasons_content)
    $("#system_rss_seasons_btn").unbind('click').click(function () {
      $("#system-rss-seasons").modal('hide');
      let rss_seasons = select_GetSelectedVAL("system_rss_season");
      if (rss_seasons.length > 0) {
        add_rss_media(name, year, type, mediaid, '', rss_seasons, func);
      }
    });
    $("#system-rss-seasons").modal('show');
  }

  //搜索
  function search_mediainfo_media(tmdbid, title, typestr) {
    hide_mediainfo_modal();
    const param = {"tmdbid": tmdbid, "search_word": title, "media_type": typestr};
    show_refresh_process("正在搜索 " + title + " ...", "search");
    ajax_post("search", param, function (ret) {
      hide_refresh_process();
      if (ret.code === 0) {
        navmenu('search?s=' + title);
      } else {
        show_fail_modal(ret.msg);
      }
    }, true, false);
  }

  //新增订阅
  function add_rss_manual(flag) {
    const mtype = $("#rss_type").val();
    const name = $("#rss_name").val();
    const year = $("#rss_year").val();
    const keyword = $("#rss_keyword").val();
    const season = $("#rss_season").val();
    const fuzzy_match = $("#fuzzy_match").prop("checked");
    const mediaid = $("#rss_tmdbid").val();
    const over_edition = $("#over_edition").prop("checked");
    const filter_restype = $("#rss_restype").val();
    const filter_pix = $("#rss_pix").val();
    const filter_team = $("#rss_team").val();
    const filter_rule = $("#rss_rule").val();
    const save_path = $("#rss_save_path").val();
    const download_setting = $("#rss_download_setting").val();
    const total_ep = $("#rss_total_ep").val();
    const current_ep = $("#rss_current_ep").val();
    const rssid = $("#rss_id").val();
    if (!name) {
      $("#rss_name").addClass("is-invalid");
      return;
    } else {
      $("#rss_name").removeClass("is-invalid");
    }
    if (year && isNaN(year)) {
      $("#rss_year").addClass("is-invalid");
      return;
    } else {
      $("#rss_year").removeClass("is-invalid");
    }
    if (!fuzzy_match && !season && (mtype == "TV" || mtype == "电视剧")) {
      $("#rss_season").addClass("is-invalid");
      return;
    } else {
      $("#rss_season").removeClass("is-invalid");
    }
    if (total_ep && isNaN(total_ep)) {
      $("#rss_total_ep").addClass("is-invalid");
      return;
    } else {
      $("#rss_total_ep").removeClass("is-invalid");
    }
    if (current_ep && isNaN(current_ep)) {
      $("#rss_current_ep").addClass("is-invalid");
      return;
    } else {
      $("#rss_current_ep").removeClass("is-invalid");
    }
    //订阅站点
    let rss_sites = select_GetSelectedVAL("rss_sites");
    if (rss_sites.length === RSS_SITES_LENGTH) {
      rss_sites = [];
    }
    //搜索站点
    let search_sites = [];
    if (!fuzzy_match) {
      search_sites = select_GetSelectedVAL("search_sites");
      if (search_sites.length === SEARCH_SITES_LENGTH) {
        search_sites = [];
      }
    }
    // 储存订阅设置
    const rss_setting = {
      "filter_restype": filter_restype,
      "filter_pix": filter_pix,
      "filter_team": filter_team,
      "filter_rule": filter_rule,
      "save_path": save_path,
      "download_setting": download_setting,
      "rss_sites": rss_sites,
      "search_sites": search_sites
    };
    if (mtype === "TV") {
      localStorage.setItem("RssSettingTV", JSON.stringify(rss_setting));
    } else if (mtype === "MOV") {
      localStorage.setItem("RssSettingMOV", JSON.stringify(rss_setting));
    }
    const data = {...{
      "type": mtype,
      "name": name,
      "year": year,
      "season": season,
      "fuzzy_match": fuzzy_match,
      "mediaid": mediaid,
      "over_edition": over_edition,
      "total_ep": total_ep,
      "current_ep": current_ep,
      "rssid": rssid,
      "keyword": keyword
    }, ...rss_setting};
    $("#modal-manual-rss").modal("hide");
    ajax_post("add_rss_media", data, function (ret) {
      if (ret.code === 0) {
        if (CURRENT_PAGE_URI.startsWith("tv_rss") || CURRENT_PAGE_URI.startsWith("movie_rss")) {
          window_history_refresh();
        } else {
          show_rss_success_modal(ret.rssid, type, name + " 添加订阅成功！");
        }
        if (flag) {
          show_add_rss_media_modal(mtype);
        }
      } else {
        if (CURRENT_PAGE_URI.startsWith("tv_rss") || CURRENT_PAGE_URI.startsWith("movie_rss")) {
          show_fail_modal(`${ret.name} 订阅失败：${ret.msg}！`, function () {
            $("#modal-manual-rss").modal("show");
          });
        } else {
          show_fail_modal(`${ret.name} 订阅失败：${ret.msg}！`);
        }
      }
    });
  }

  //初始化下拉框
  let rss_season_content = `<option value="">请选择</option>`;
  for (let i = 0; i <= 50; i++) {
    rss_season_content += `<option value="${i}">第${i}季</option>`;
  }
  $("#rss_season").empty().append(rss_season_content);

  // 选择模糊匹配
  function change_match_check(obj) {
    if ($(obj).prop("checked")) {
      $("#rss_search_sites_div").hide();
      $("#over_edition").prop("checked", false);
    } else {
      $("#rss_search_sites_div").show();
    }
  }

  // 选择洗版
  function change_over_edition_check(obj) {
    if ($(obj).prop("checked")) {
      $("#fuzzy_match").prop("checked", false);
      $("#rss_search_sites_div").show();
    }
  }

  //取消订阅
  function remove_rss_manual(type, name, year, rssid) {
    $("#modal-manual-rss").modal('hide');
    let page;
    if (CURRENT_PAGE_URI.startsWith("tv_rss")) {
      page = "tv_rss";
    } else if (CURRENT_PAGE_URI.startsWith("movie_rss")) {
      page = "movie_rss";
    } else {
      page = undefined
    }
    remove_rss_media(name, year, type, rssid, page);
  }

  // 新增订阅
  function show_add_rss_media_modal(mtype) {
    // 刷新下拉框
    refresh_rss_download_setting_dirs();
    // 界面初始化
    $("#rss_id").val("");
    $("#rss_modal_title").text("新增订阅");
    $("#rss_name").val("").attr("readonly", false);
    $("#rss_year").val("").attr("readonly", false);
    $("#rss_keyword").val("");
    $("#rss_tmdbid").val("");
    $("#fuzzy_match").prop("checked", false);
    $("#over_edition").prop("checked", false);
    $("#rss_season").val("");
    $("#rss_total_ep").val("");
    $("#rss_current_ep").val("");
    let rss_setting;
    if (mtype === "TV") {
      $("#rss_type").val("TV");
      $("#rss_tv_season_div").show();
      rss_setting = localStorage.getItem("RssSettingTV");
    } else if (mtype === "MOV") {
      $("#rss_type").val("MOV");
      $("#rss_tv_season_div").hide();
      rss_setting = localStorage.getItem("RssSettingMOV");
    }
    if (rss_setting) {
      rss_setting = JSON.parse(rss_setting);
      $("#rss_restype").val(rss_setting.filter_restype);
      $("#rss_pix").val(rss_setting.filter_pix);
      $("#rss_team").val(rss_setting.filter_team);
      $("#rss_rule").val(rss_setting.filter_rule);
      $("#rss_download_setting").val(rss_setting.download_setting);
      refresh_savepath_select('rss_save_path', false, rss_setting.download_setting)
      $("#rss_save_path").val(rss_setting.save_path);
      if (rss_setting.search_sites.length === 0) {
        select_SelectALL(true, 'search_sites')
      } else {
        select_SelectPart(rss_setting.search_sites, 'search_sites');
      }
      if (rss_setting.rss_sites.length === 0) {
        select_SelectALL(true, 'rss_sites')
      } else {
        select_SelectPart(rss_setting.rss_sites, 'rss_sites');
      }
    } else {
      $("#rss_restype").val('');
      $("#rss_pix").val('');
      $("#rss_team").val('');
      $("#rss_rule").val('');
      $("#rss_save_path").val('');
      $("#rss_download_setting").val('');
      select_SelectALL(false, "rss_sites");
      select_SelectALL(false, "search_sites");
    }
    $("[name='rss_edit_btn']").hide();
    $("[name='rss_add_btn']").show();
    $("#rss_delete_btn").hide();
    $("#modal-manual-rss").modal('show');
  }

  // 显示编辑订阅
  function show_edit_rss_media_modal(rssid, type) {
    $("#system-media-modal").modal('hide');
    $("#rss_id").val(rssid);
    $("#rss_type").val(type);
    $("#rss_modal_title").text("编辑订阅");

    // 刷新下拉框
    refresh_rss_download_setting_dirs();

    // 获取订阅信息
    ajax_post("rss_detail", {"rssid": rssid, "rsstype": type}, function (ret) {
      if (ret.code === 0) {
        $("#rss_tmdbid").val(ret.detail.tmdbid);
        $("#rss_name").val(ret.detail.name).attr("readonly", true);
        $("#rss_year").val(ret.detail.year).attr("readonly", true);
        $("#rss_keyword").val(ret.detail.keyword);
        if (type == "MOV" || type == "电影") {
          $("#rss_tv_season_div").hide();
          $("#rss_season").val("");
          $("#rss_total_ep").val("");
          $("#rss_current_ep").val("");
        } else {
          $("#rss_tv_season_div").show();
          if (ret.detail.season) {
            $("#rss_season").val(parseInt(ret.detail.season.replace("S", "")));
          } else {
            $("#rss_season").val("");
          }
          if (ret.detail.total_ep) {
            $("#rss_total_ep").val(ret.detail.total_ep);
          } else {
            $("#rss_total_ep").val("");
          }
          if (ret.detail.current_ep) {
            $("#rss_current_ep").val(ret.detail.current_ep);
          } else {
            $("#rss_current_ep").val("");
          }
        }
        if (!ret.detail.fuzzy_match) {
          $("#fuzz_match").prop("checked", false);
          $("#rss_search_sites_div").show();
        } else {
          $("#fuzzy_match").prop("checked", true);
          $("#rss_search_sites_div").hide();
        }
        if (ret.detail.over_edition) {
          $("#over_edition").prop("checked", true);
        } else {
          $("#over_edition").prop("checked", false);
        }
        $("#rss_restype").val(ret.detail.filter_restype);
        $("#rss_pix").val(ret.detail.filter_pix);
        $("#rss_team").val(ret.detail.filter_team);
        $("#rss_rule").val(ret.detail.filter_rule);
        $("#rss_download_setting").val(ret.detail.download_setting);
        refresh_savepath_select('rss_save_path', false, ret.detail.download_setting)
        $("#rss_save_path").val(ret.detail.save_path);
        if (ret.detail.rss_sites.length === 0) {
          select_SelectALL(true, 'rss_sites');
        } else {
          select_SelectPart(ret.detail.rss_sites, 'rss_sites')
        }
        if (ret.detail.search_sites.length === 0) {
          select_SelectALL(true, 'search_sites');
        } else {
          select_SelectPart(ret.detail.search_sites, 'search_sites')
        }
        $("[name='rss_add_btn']").hide();
        $("[name='rss_edit_btn']").show();
        $("#rss_delete_btn").attr("href",
            `javascript:remove_rss_manual('${ret.detail.type}','${ret.detail.name}','${ret.detail.year}','${rssid}')`)
            .show();
        $("#modal-manual-rss").modal('show');
      }
    });
  }

  // 显示订阅成功（带后续操作）
  function show_rss_success_modal(rssid, type, text) {
    $("#system_success_action_message").text(text);
    if (rssid) {
      $("#system_success_action_btn").text("编辑订阅")
          .unbind('click').click(function () {
        $("#system-success-action-modal").modal('hide');
        show_edit_rss_media_modal(rssid, type);
      });
      ;
      $("#system_success_action_div").show();
    } else {
      $("#system_success_action_div").hide();
    }
    $("#system-success-action-modal").modal('show');
  }

  // 刷新规则下拉框
  function refresh_filter_select(obj_id, aync = true) {
    ajax_post("get_filterrules", {}, function (ret) {
      if (ret.code === 0) {
        let rule_select = $(`#${obj_id}`);
        let rule_select_content = `<option value="">站点规则</option>`;
        for (let ruleGroup of ret.ruleGroups) {
          rule_select_content += `<option value="${ruleGroup.id}">${ruleGroup.name}</option>`;
        }
        rule_select.empty().append(rule_select_content);
      }
    }, aync);
  }

  // 刷新订阅站点列表
  var RSS_SITES_LENGTH = 0;
  function refresh_rsssites_select(obj_id, item_name,aync = true) {
    ajax_post("get_sites", {rss: true, basic: true}, function (ret) {
      if (ret.code === 0) {
        let rsssites_select = $(`#${obj_id}`);
        let rsssites_select_content = "";
        RSS_SITES_LENGTH = ret.sites.length;
        if (ret.sites.length > 0) {
          rsssites_select.parent().parent().show();
        } else {
          rsssites_select.parent().parent().hide();
        }
        for (let site of ret.sites) {
          rsssites_select_content += `
          <label class="form-selectgroup-item">
            <input type="checkbox" name="${item_name}" value="${site.name}" class="form-selectgroup-input">
            <span class="form-selectgroup-label">${site.name}</span>
          </label>`;
        }
        rsssites_select.empty().append(rsssites_select_content);
      }
    }, aync);
  }

  // 刷新搜索站点列表
  var SEARCH_SITES_LENGTH = 0;
  function refresh_searchsites_select(obj_id, item_name,aync = true) {
    ajax_post("get_indexers", {check: true, basic: true}, function (ret) {
      if (ret.code === 0) {
        let searchsites_select = $(`#${obj_id}`);
        let searchsites_select_content = "";
        SEARCH_SITES_LENGTH = ret.indexers.length;
        if (ret.indexers.length > 0) {
          searchsites_select.parent().parent().show();
        } else {
          searchsites_select.parent().parent().hide();
        }
        for (let indexer of ret.indexers) {
          searchsites_select_content += `
          <label class="form-selectgroup-item">
            <input type="checkbox" name="${item_name}" value="${indexer.name}" class="form-selectgroup-input">
            <span class="form-selectgroup-label">${indexer.name}</span>
          </label>`;
        }
        searchsites_select.empty().append(searchsites_select_content);
      }
    }, aync);
  }


  function refresh_site_options(obj_id, show_all=false) {
    ajax_post("get_indexers", {check: true, basic: true}, function (ret) {
      if (ret.code === 0) {
        let site_options = '';
        if (show_all) {
          site_options += `<option value="">全部</option>`;
        }
        for (let indexer of ret.indexers) {
          site_options += `<option value="${indexer.name}">${indexer.name}</option>`;
        }
        $(`#${obj_id}`).empty().append(site_options);
      }
    });
  }

  // 刷新保存路径
  function refresh_savepath_select(obj_id, aync = true, sid = "", is_default = false, site="") {
    let savepath_select = $(`#${obj_id}`);
    if (!sid && !is_default && !site) {
      savepath_select.empty().append(`<option value="" selected>自动</option>`);
    } else {
      ajax_post("get_download_dirs", {sid: sid, site: site}, function (ret) {
        if (ret.code === 0) {
          let savepath_select_content = `<option value="" selected>自动</option>`;
          for (let path of ret.paths) {
            savepath_select_content += `<option value="${path}">${path}</option>`;
          }
          savepath_select.empty().append(savepath_select_content);
        }
      }, aync);
    }
  }

  // 刷新下载设置
  function refresh_downloadsetting_select(obj_id, aync = true, is_default = false) {
    let default_content = (!is_default) ? "站点设置" : "默认";
    ajax_post("get_download_setting", {}, function (ret) {
      if (ret.code === 0) {
        let downloadsetting_select = $(`#${obj_id}`);
        let downloadsetting_select_content = `<option value="" selected>${default_content}</option>`;
        for (let downloadsetting of ret.data) {
          downloadsetting_select_content += `<option value="${downloadsetting.id}">${downloadsetting.name}</option>`;
        }
        downloadsetting_select.empty().append(downloadsetting_select_content);
      }
    }, aync);
  }

  // 刷新订阅框的下载设置及目录等选项
  function refresh_rss_download_setting_dirs(){
    refresh_rsssites_select("rss_sites_group", "rss_sites", false);
    refresh_searchsites_select("rss_search_sites_group", "search_sites", false);
    refresh_filter_select("rss_rule", false);
    refresh_downloadsetting_select("rss_download_setting", false);
    refresh_savepath_select("rss_save_path", false, $("#rss_download_setting").val());
  }

  // 刷新下载框的下载设置及目录选项
  function refresh_search_download_setting_dirs(is_default, site=""){
    refresh_downloadsetting_select("search_download_setting", false, is_default);
    refresh_savepath_select("search_download_dir", true, $("#search_download_setting").val(), is_default, site);
  }

  // 显示下载提示框
  function show_download_modal(id, name, site=undefined, func=undefined, show_type=undefined) {
    $("#search_download_id").val(id);
    $("#search_download_name").val(name);
    $("#search_download_message").text(`新增下载 ${name}`);
    // 根据下载设置刷新下载目录选项
    // 正在下载页面新增下载添加默认而非站点设置
    if (show_type) {
      refresh_search_download_setting_dirs(true);
      $("#search_download_setting").attr("onchange", "refresh_savepath_select('search_download_dir', true, $(this).val(), true)")
    } else if (site) {
      refresh_search_download_setting_dirs(false, site);
      $("#search_download_setting").attr("onchange", `refresh_savepath_select('search_download_dir', true, $(this).val(), false, "${site}")`)
    } else {
      refresh_search_download_setting_dirs(false);
      $("#search_download_setting").attr("onchange", "refresh_savepath_select('search_download_dir', true, $(this).val(), false)")
    }

    // 绑定下载按钮事件
    if (func) {
      $("#search_download_btn").unbind("click").click(func);
    }else{
      $("#search_download_btn").unbind("click").click(download_link);
    }
    // 清空
    torrent_dropzone.removeAllFiles();
    $("#torrent_magnets").val("");
    if (show_type === 'torrent') {
      $("#torrent_files").show();
      $("#torrent_magnets").hide();
    } else if (show_type === 'magnet') {
      $("#torrent_magnets").show();
      $("#torrent_files").hide();
    } else {
      $("#torrent_files").hide();
      $("#torrent_magnets").hide();
    }
    $("#modal-search-download").modal('show');
  }

  //点击链接下载
  function download_link() {
    const id = $("#search_download_id").val();
    const name = $("#search_download_name").val();
    const dir = $("#search_download_dir").val();
    const setting = $("#search_download_setting").val();
    $("#modal-search-download").modal('hide');
    ajax_post("download", {"id": id, "dir": dir, "setting": setting}, function (ret) {
      if (ret.retcode === 0) {
        show_success_modal(`${name} 添加下载成功！`);
      } else {
        show_fail_modal(`${name} 添加下载失败 ${ret.retmsg}！`);
      }
    });
  }

  // 显示高级搜索框
  function show_search_advanced_modal() {
    refresh_site_options("advanced_search_site", true);
    refresh_filter_select("advanced_search_rule");
    $("#modal-search-advanced").modal("show");
  }

  // 开始高级搜索
  function search_media_advanced() {
    let keyword;
    // 读取数据
    const search_name = $("#advanced_search_name").val();
    if (!search_name) {
      $("#advanced_search_name").addClass("is-invalid");
      return;
    } else {
      $("#advanced_search_name").removeClass("is-invalid");
    }
    const search_type = $("#advanced_search_type").val();
    const search_season = $("#advanced_search_season").val();
    const search_year = $("#advanced_search_year").val();
    const search_site = $("#advanced_search_site").val();
    const search_restype = $("#advanced_search_restype").val();
    const search_pix = $("#advanced_search_pix").val();
    const sp_state = $("#advanced_sp_state").val();
    const search_rule = $("#advanced_search_rule").val();
    // 拼装请求
    if (search_type) {
      keyword = search_type + " " + search_name;
    } else {
      keyword = search_name;
    }
    if (search_year) {
      keyword = keyword + " " + search_year;
    }
    if (search_season) {
      keyword = keyword + " " + search_season;
    }
    const filters = {
      "site": search_site,
      "restype": search_restype,
      "pix": search_pix,
      "sp_state": sp_state,
      "rule": search_rule
    };
    const param = {"search_word": keyword, "filters": filters, "unident": true};
    $("#modal-search-advanced").modal("hide");
    show_refresh_process(`正在搜索 ${keyword} ...`, "search");
    ajax_post("search", param, function (ret) {
      hide_refresh_process();
      if (ret.code === 0) {
        navmenu(`search?s=${keyword}`);
      } else {
        show_fail_modal(ret.msg,function () {
          $("#modal-search-advanced").modal("show");
        });
      }
    }, true, false);
  }

</script>

<!-- 页面组件 -->
<script type="text/javascript">

  //刷新tooltip
  function fresh_tooltip() {
    const tooltipTriggerList = Array.prototype.slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
      return new bootstrap.Tooltip(tooltipTriggerEl)
    });
  }

  //打开路径选择框
  function openFileBrowser(el, root, filter, on_folders, on_files, close_on_select) {
    if (on_folders === undefined) on_folders = true;
    if (on_files === undefined) on_files = true;
    if (!filter && !on_files) filter = 'HIDE_FILES_FILTER';
    if (!root.trim()) root = "/";
    let p = $(el);
    // Skip is fileTree is already open
    if (p.next().hasClass('fileTree')) return null;
    // create a random id
    const r = Math.floor((Math.random() * 1000) + 1);
    // Add a new span and load fileTree
    p.after("<div id='fileTree" + r + "' class='fileTree card shadow-sm' style='z-index: 99999'></div>");
    const ft = $('#fileTree' + r);
    ft.fileTree({
          script: 'dirlist',
          root: root,
          filter: filter,
          allowBrowsing: true
        },
        function (file) {
          if (on_files) {
            p.val(file);
            p.trigger('change');
            if (close_on_select) {
              ft.slideUp('fast', function () {
                ft.remove();
              });
            }
          }
        },
        function (folder) {
          if (on_folders) {
            p.val(folder);
            p.trigger('change');
            if (close_on_select) {
              $(ft).slideUp('fast', function () {
                $(ft).remove();
              });
            }
          }
        });
    // Format fileTree according to parent position, height and width
    ft.css({'left': p.position().left, 'top': (p.position().top + p.outerHeight()), 'width': (p.parent().width())});
    // close if click elsewhere
    $(document).mouseup(function (e) {
      if (!ft.is(e.target) && ft.has(e.target).length === 0) {
        ft.slideUp('fast', function () {
          $(ft).remove();
        });
      }
    });
    // close if parent changed
    p.bind("keydown", function () {
      ft.slideUp('fast', function () {
        $(ft).remove();
      });
    });
    // Open fileTree
    ft.slideDown('fast');
  }

  //初始化目录选择控件
  function init_filetree_element() {
    $('.filetree-folders-only').each(function () {
      $(this).attr("onclick", "openFileBrowser(this,$(this).val(),'',true,false);");
    });
    $('.filetree-files-only').each(function () {
      $(this).attr("onclick", "openFileBrowser(this,$(this).val(),'',false,true);");
    });
  }

  // 名称识别测试
  function media_name_test(name, result_div, func) {
    if (!name) {
      return;
    }
    ajax_post("name_test", {"name": name}, function (ret) {
      if (func) {
        func();
      }
      if (ret.code === 0) {
        media_name_test_ui(ret.data, result_div);
      }
    });
  }

  // 处理识别结果UI
  function media_name_test_ui(data, result_div) {
    // 希望chips按此数组的顺序生成..
    $(`#${result_div}`).empty();
    const sort_array = ["org_string", "ignored_words", "replaced_words", "offset_words",
                        "type","category","name","title","tmdbid","year","season_episode","part",
                        "restype","effect","pix","video_codec","audio_codec","team"]
    // 调用组件实例的自定义方法.. 一次性添加chips
    document.querySelector(`#${result_div}`).add_chips_all(sort_array, data);
  }

  // 显示手动识别转移框
  // manual_type: 1-未识别手动识别，2-历史记录手动识别，3-自定义识别
  // media_type: 电影，电视剧，动漫
  function show_manual_transfer_modal(manual_type, inpath, syncmod, media_type, unknown_id, transferlog_id) {
    // 初始化类型
    if (!syncmod) {
      syncmod = '{{ SyncMod }}';
    }
    let source = CURRENT_PAGE_URI;
    $("#rename_source").val(source);
    $("#rename_manual_type").val(manual_type);
    if (manual_type === 3) {
      $('#rename_header').text("自定义识别");
      $('#rename_path_div').hide();
      $('#rename_inpath_div').show();
      $('#rename_outpath_div').show();
      $("#rename_inpath").val(inpath);
      $("#rename_outpath").val('');
      $("#rename_syncmod_customize").val(syncmod);
      $("#unknown_id").val("");
      $("#transferlog_id").val("");
    } else {
      $('#rename_header').text("手动识别");
      $('#rename_path_div').show();
      $('#rename_inpath_div').hide();
      $('#rename_outpath_div').hide();
      $("#rename_path").val(inpath);
      $("#rename_syncmod_manual").val(syncmod);
      $("#unknown_id").val(unknown_id);
      $("#transferlog_id").val(transferlog_id);
    }

    // 初始化媒体类型
    if (media_type === "电视剧") {
      $("#rename_type_tv").prop("checked", true);
      $("#rename_type_mov").removeProp("checked");
      $("#rename_type_anime").removeProp("checked");
      $("#rename_season_div").show();
      $("#rename_episode_div").show();
    } else if (media_type === "动漫") {
      $("#rename_type_anime").prop("checked", true);
      $("#rename_type_tv").removeProp("checked");
      $("#rename_type_mov").removeProp("checked");
      $("#rename_season_div").show();
      $("#rename_episode_div").show();
    } else {
      $("#rename_type_mov").prop("checked", true);
      $("#rename_type_tv").removeProp("checked");
      $("#rename_type_anime").removeProp("checked");
      $("#rename_season_div").hide();
      $("#rename_episode_div").hide();
      $("#rename_season").val("");
    }

    // 清空输入框
    $("#rename_min_filesize").val("");
    $("#rename_episode").val("");
    $("#rename_episode_details").val("");
    $("#rename_episode_offset").val("");
    $("#rename_season").val("");
    $("#rename_tmdb").val("");

    // 显示窗口
    $("#modal-media-identification").modal("show");

  }


  // 重新识别
  function re_identification(flag, ids) {
    ajax_post("re_identification", {"flag": flag, "ids": ids}, function (ret) {
        if (ret.retcode == 0) {
        navmenu(flag);
        } else {
        show_fail_modal(`重新识别失败：${ret.retmsg}！`);
        }
    });
  }

  // 执行手动识别转移
  function manual_media_transfer() {
    let syncmod;
    const source = $("#rename_source").val();
    const manual_type = $("#rename_manual_type").val();
    const type = $('input:radio[name=rename_type]:checked').val();
    const path = $("#rename_path").val();
    const inpath = $("#rename_inpath").val();
    const outpath = $("#rename_outpath").val();
    if (manual_type == '3') {
      syncmod = $("#rename_syncmod_customize").val();
    } else {
      syncmod = $("#rename_syncmod_manual").val();
    }
    const tmdb = $("#rename_tmdb").val();
    const season = $("#rename_season").val();
    const episode_format = $("#rename_episode").val();
    const episode_details = $("#rename_episode_details").val();
    const episode_offset = $("#rename_episode_offset").val();
    const min_filesize = $("#rename_min_filesize").val();
    const logid = $("#transferlog_id").val();
    const unknown_id = $('#unknown_id').val();

    if (manual_type == '1' && !unknown_id) {
      return;
    }

    if (manual_type == '2' && !logid) {
      return;
    }

    if (manual_type == '3') {
      if (!inpath) {
        $("#rename_inpath").addClass("is-invalid");
        return;
      } else {
        $("#rename_inpath").removeClass("is-invalid");
      }
    } else {
      if (!path) {
        $("#rename_path").addClass("is-invalid");
        return;
      } else {
        $("#rename_path").removeClass("is-invalid");
      }
    }

    if (min_filesize && isNaN(min_filesize)) {
      $("#rename_min_filesize").addClass("is-invalid");
      return;
    } else {
      $("#rename_min_filesize").removeClass("is-invalid");
    }

    if (episode_details && !/^\d{1,5}([,-]\d{1,5})?$/.test(episode_details)) {
      $("#rename_episode_details").addClass("is-invalid");
      return;
    } else {
      $("#rename_episode_details").removeClass("is-invalid");
    }
    if (episode_offset && !/^-?\d{1,5}$/.test(episode_offset)) {
      $("#rename_episode_offset").addClass("is-invalid");
      return;
    } else {
      $("#rename_episode_offset").removeClass("is-invalid");
    }

    if ((episode_details || episode_offset) && !episode_format) {
      $("#rename_episode").addClass("is-invalid");
      return;
    } else {
      $("#rename_episode").removeClass("is-invalid");
    }

    // 开始处理
    const data = {
      "inpath": inpath,
      "outpath": outpath,
      "syncmod": syncmod,
      "type": type,
      "tmdb": tmdb,
      "season": season,
      "episode_format": episode_format,
      "episode_details": episode_details,
      "episode_offset": episode_offset,
      "min_filesize": min_filesize,
      "unknown_id": unknown_id,
      "path": path,
      "logid": logid
    };
    $('#modal-media-identification').modal('hide');
    show_refresh_process("手动转移 " + inpath, "filetransfer");
    let cmd = (manual_type === '3') ? "rename_udf" : "rename"
    ajax_post(cmd, data, function (ret) {
      hide_refresh_process();
      if (ret.retcode === 0) {
        show_success_modal(inpath + "处理成功！", function () {
          navmenu(source);
        });
      } else {
        //处理失败
        show_fail_modal(ret.retmsg, function(){
          $('#modal-media-identification').modal('show');
        });
      }
    });
  }

  // 查示查询TMDBID的对话框
  function show_search_tmdbid_modal(val_obj, modal_id){
    $("#"+modal_id).modal("hide");
    $("#search_tmdbid_btn").unbind("click").click(function(){
      let tmdbid = $("#search_tmdbid_list input:radio[name=search_tmdbid_check]:checked").val();
      $("#"+val_obj).val(tmdbid);
      $("#search-tmdbid-modal").modal("hide");
      $("#"+modal_id).modal("show");
    });
    $("#search-tmdbid-modal").modal("show");
  }

  //根据名称查询TMDBID
  function search_tmdbid_by_name(keyid, resultid){
    let name = $("#"+keyid).val();
    if (!name) {
      $("#"+keyid).addClass("is-invalid");
      return;
    } else {
      $("#"+keyid).removeClass("is-invalid");
    }
    $("#"+keyid).prop("disabled", true);
    ajax_post("search_media_infos", {"keyword": name, "searchtype": "tmdb"}, function(ret){
      $("#"+keyid).prop("disabled", false);
      if(ret.code == 0){
        let data = ret.result;
        let html = '';
        if (data.length > 0) {
          for(let i=0; i<data.length; i++){
            html += `<div class="list-group-item" onclick="$(this).find('input:radio').prop('checked', true);"><div class="row align-items-center">`;
            html += `<div class="col-auto"><input type="radio" name="search_tmdbid_check" value="${data[i].tmdb_id}" class="form-check-input"></div>`;
            html += `<div class="col-auto"><img class="rounded w-5 shadow-sm" src="${data[i].image}" onerror="this.src='../static/img/no-image.png'"></div>`;
            html += `<div class="col text-truncate"><a href="${data[i].link}" target="_blank" class="text-reset d-block">${data[i].title} (${data[i].year})</a><div class="text-muted mt-n1 text-wrap" style="-webkit-line-clamp:3; display: -webkit-box; -webkit-box-orient:vertical; overflow:hidden; text-overflow: ellipsis;">${data[i].overview}</div></div>`;
            html += `</div></div>`;
          }
          $("#"+resultid).html(html);
        } else {
          $("#"+resultid).html('<div class="list-group-item text-center text-muted">未找到相关信息</div>');
        }
      } else {
        $("#"+resultid).html(`<div class="list-group-item text-center text-muted">${ret.msg}</div>`);
      }
    });
  }

  //初始化季列表
  function init_season_list() {
    let rename_season_content = `<option value="" selected>请选择</option>`;
    let search_season_content = `<option value="" selected>全部</option>`;
    for (let i = 0; i <= 50; i++) {
      rename_season_content += `<option value="${i}">第${i}季</option>`;
      if (i > 0) {
        search_season_content += `<option value="${i}">第${i}季</option>`;
      }
    }
    $("#rename_season").empty().append(rename_season_content);
    $("#advanced_search_season").empty().append(search_season_content);
  }

</script>

<!-- 首页功能 -->
<script type="text/javascript">
  //当前页面地址
  let CURRENT_PAGE_URI = "";

  function window_history_refresh() {
    if (window.history.state?.page) {
      navmenu(window.history.state.page, true);
    }
  }

  function window_history(newflag=false, extra=undefined){
    const state = {
      title: document.title,
      html: $("#page_content").html(),         // 页面内容
      scroll: $(".page").scrollTop(),  // 页面滚动位置
      CurrentPage: sessionStorage.CurrentPage, // 页面当前页码
      page: CURRENT_PAGE_URI,                  // 当前页面地址
      extra: extra,                            // 额外的保存数据
    };
    if (newflag) {
      window.history.pushState(state, "");
    } else {
      // 当未传递extra时的页面缓存刷新, 应当重新保留extra数据
      if (!extra && window.history.state?.extra) {
        state.extra = window.history.state.extra;
      }
      window.history.replaceState(state, "");
    }
  }

  //刷新LOG标志
  let refresh_logging_flag = false;

  //开始刷新日志
  function start_logging() {
    refresh_logging_flag = true;
    refresh_logging();
  }

  //停止刷新日志
  function stop_logging() {
    refresh_logging_flag = false;
  }

  // 日志来源筛选时关掉之前的刷新日志计时器
  var refresh_logging_timer
  let logger_source = "";

  //刷新日志
  function refresh_logging(flag) {
    let refresh_new = $("#logging_content").children().length;
    ajax_post("logging", {"refresh_new": refresh_new, "source": logger_source}, function (ret) {
      if (ret.loglist) {
        let log_list = ret.loglist;
        let tdstyle = "padding-top: 0.5rem; padding-bottom: 0.5rem";
        let tbody = "";
        for (let log of log_list) {
          let text = log.text;
          const source = log.source;
          const time = log.time;
          const level = log.level;
          let tcolor = '';
          let bgcolor = '';
          let tstyle = '';
          if (level === "WARN") {
            tcolor = "text-warning";
            bgcolor = "bg-warning";
          } else if (level === "ERROR") {
            tcolor = "text-danger";
            bgcolor = "bg-danger";
          } else if (source === "System") {
            tcolor = "text-info";
            bgcolor = "bg-info";
          } else {
            tcolor = "text";
          }
          if (["Rmt", "Subtitle"].includes(source) && text.includes(" 到 ")) {
            tstyle = `white-space: pre;`
            text = text.replace(/\s到\s/, "\n=> ")
          }
          if (text.includes("http") || text.includes("magnet")) {
            tstyle = `word-break: break-all;`
            text = text.replace(/：((?:http|magnet).+?)(?:\s|$)/g, "：<a href='$1' target='_blank'>$1</a>")
          }
          tbody = `${tbody}
                    <tr>
                    <td style="${tdstyle}"><span class="${tcolor}">${time}</span></td>
                    <td style="${tdstyle}"><span class="badge ${bgcolor}">${source}</span></td>
                    <td style="${tdstyle}"><span class="${tcolor}" style="${tstyle}">${text}</span></td>
                    </tr>`;
        }
        let logging_table_obj = $("#logging_table");
        let bool_ToScrolTop = (logging_table_obj.scrollTop() + logging_table_obj.prop("offsetHeight")) >= logging_table_obj.prop("scrollHeight");
        $("#logging_content").append(tbody);
        if (bool_ToScrolTop){
          setTimeout(function () {
            logging_table_obj.scrollTop(logging_table_obj.prop("scrollHeight"));
          }, 500);
        }
      }
      if ($("#modal-logging").is(":hidden") && flag) {
        stop_logging();
      }
      if (refresh_logging_flag === true) {
        refresh_logging_timer = window.setTimeout("refresh_logging(true)", 2000);
      }
    }, true, false);
  }

  //暂停实时日志
  function pause_logging() {
    if (refresh_logging_flag === true) {
      stop_logging();
      $("#logging_stop_btn").text("开始")
    } else {
      start_logging();
      $("#logging_stop_btn").text("暂停")
    }
  }

  //实时日志关闭
  $("#logging_close_btn").unbind("click").click(function () {
    stop_logging();
     // 清空日志
    $("#logging_content").html("")
    logger_source = ""
  });

  $("#logging_close_head").unbind("click").click(function () {
    stop_logging();
     // 清空日志
    $("#logging_content").html("")
    logger_source = ""
  });

  // 显示实时日志
  function show_logging_modal() {
    start_logging();
    $('#modal-logging').modal('show');
  }

  // 渲染日志来源下拉列表
  function get_logging_source(){
    $("#dropdown-menu-logger").html('')
    var menu=['All', 'System', 'Rss', 'Rmt', 'Meta', 'Sync', 'Sites', 'Brush', 'Douban', 'Spider', 'Message', 'Indexer', 'Searcher', 'Subscribe', 'Downloader', 'TorrentRemover']
    for(var i=0;i<menu.length;i++){
      $("#dropdown-menu-logger").append(`<a class="dropdown-item"  href="javascript:logger_select('${menu[i]}')">${menu[i]}</a>`);
    }
  }

  // 日志来源筛选
  function logger_select(source){
    logger_source = source
    if (logger_source === "All") logger_source = "";

    // 关闭之前的定时刷新日志
    clearTimeout(refresh_logging_timer)

    // 清空日志
    $("#logging_content").html("")

    // 重新拉取日志
    refresh_logging()
  }

  //刷新消息中心
  function refresh_message(time_str) {
    ajax_post("refresh_message", {"lst_time": time_str}, function (ret) {
      if (ret.code === 0) {
        let lst_time = ret.lst_time;
        const msgs = ret.message;
        for (let i = 0; i < msgs.length; i++) {
          $("#system-messages").prepend(msgs[i]);
        }
        setTimeout("refresh_message('" + lst_time + "')", 10000);
      }
    }, true, false);
  }

  //检查系统是否在线
  function check_system_online() {
    ajax_post("refresh_process", {type: "restart"}, function (ret) {
        if (ret.code === -1) {
          logout();
        } else {
          setTimeout("check_system_online()", 1000);
        }
      }, true, false)
  }

  //注销
  function logout() {
    ajax_post("logout", {}, function (ret) {
      window.location.href = "/";
    });
  }

  //重启
  function restart() {
    show_confirm_modal("立即重启系统？", function () {
      hide_confirm_modal();
      ajax_post("restart", {}, function (ret) {
      }, true, false);
      show_wait_modal(true);
      setTimeout("check_system_online()", 5000);
    });
  }

  //更新
  function update(version) {
    let title;
    if (version) {
      title = "是否确认更新到 " + version + " 版本？";
    } else {
      title = "将从Github拉取最新程序代码并重启，是否确认？";
    }
    show_confirm_modal(title, function () {
      hide_confirm_modal();
      ajax_post("update_system", {}, function (ret) {
      }, true, false)
      show_wait_modal(true);
      setTimeout("check_system_online()", 5000);
    });
  }

  //导航点击
  function navmenu(page, newflag=false) {
    if (!newflag) {
      // 更新当前历史记录
      window_history();
    }
    // 主动点击时清除页码, 刷新页面也需要清除
    sessionStorage.removeItem("CurrentPage");

    document.querySelector("#navbar-menu").update_active(page);
    $(window).unbind('scroll');
    page = page.replaceAll(" ", "%20");
    NProgress.start();
    $("#page_content").load(page, {}, function (response, status, xhr) {
      NProgress.done();
      if ($("#page_content").find("title").first().text() === "登录 - NAStool") {
        window.location.reload();
      } else {
        fresh_tooltip();
        init_filetree_element();
      }
      if (page !== CURRENT_PAGE_URI) {
        $(window).scrollTop(0);
        CURRENT_PAGE_URI = page;
      }
      // 并记录当前历史记录
      window_history(!newflag);
    });
  }

</script>

<!-- 事件  -->
<script type="text/javascript">

  // 种子上传控件
  let torrent_dropzone;

  //事件
  $(document).ready(function () {
    window.addEventListener('popstate', function(e) {
        if (e.state) {
          // 开始还原页面
          if (e.state.CurrentPage) {
            sessionStorage.CurrentPage = e.state.CurrentPage;
          }
          CURRENT_PAGE_URI = e.state.page;
          document.querySelector("#navbar-menu").update_active();
          $(window).unbind('scroll');
          document.title = e.state.title;
          $('#page_content').html(e.state.html).ready(function() {
            $(window).scrollTop(e.state.scroll);
          })
        }
    });

    // tooltip点击事件处理，阻止冒泡到上级元素，避免比如`点击tooltip切换了switch`的问题
    $('body').on('click', 'span[data-bs-toggle="tooltip"]', function (e) {
      e.preventDefault();
      e.stopPropagation();
    });

    /**
     * 计算菜单列表高度
     * @return {number}
     */
    function computeMenuListHeight() {
      // '#navbar-menu > .order-first' 要打开菜单后才会显示，所以这里取固定值36
      const menuFirstHeight = 36;
      // 这个是经过测试得到的数值
      const extra = 120;
      return $('.navbar-brand').outerHeight() + menuFirstHeight + extra
    }

    /**
     * 更新菜单列表高度
     */
    function updateMenuListHeight() {
      const height = computeMenuListHeight();
      $('.navbar ul.navbar-nav').css({
        maxHeight: 'calc(100vh - ' + height + 'px)'
      })
    }
    // 更新菜单高度
    updateMenuListHeight()

    // 初始化季列表
    init_season_list();

    // 初始化DropZone
    torrent_dropzone = new Dropzone("#torrent_files");
    torrent_dropzone.options.acceptedFiles = ".torrent";

    // 单选框事件
    $('input[type=radio][name=rename_type]').change(function () {
      if (this.value === 'MOV') {
        $("#rename_season_div").hide();
        $("#rename_episode_div").hide();
        $("#rename_season").val('');
      } else {
        $("#rename_season_div").show();
        $("#rename_episode_div").show();
      }
    });


    {% if "系统设置" in UserPris %}
      // 刷新消息
      refresh_message("");
    {% endif %}

    {% if not TMDBFlag %}
      // 检查tmdb配置
      show_fail_modal("请先配置TMDB API Key，并修改登录密码！", function () {
        navmenu('basic');
      });
    {% endif %}

  });
</script>
<!-- 动态载入自定义组件 -->
<script src="../static/components/index.js"></script>
<!-- 用户自定义CSS -->
<style>
  {{ CustomScriptCfg.css|safe or "" }}
</style>
<!-- 用户自定义JavaScript -->
<script type="text/javascript">
  {{ CustomScriptCfg.javascript|safe or "" }}
</script>
</body>
</html>
